<template>
  <div class="dg-header" :style="{height: headerHeight + 'px'}">
    <d-g-header-cell v-for="column in settings.leftFixedColumns"
                     @start-resize="startResize"
                     @check-all="onCheckAllStateChange"
                     @sort-change="onSortChange"
                     :key="column.field"
                     :column="column"
                     :level="0"
                     :root-config="rootConfig"
                     :cur-sorting="curSorting"
                     :heights="settings.heights"></d-g-header-cell>
    <div class="dg-header-normal-wrapper" :style="normalColumnsWrapperStyle">
      <div :style="normalColumnsStyle">
        <d-g-header-cell v-for="column in settings.normalColumns"
                         @start-resize="startResize"
                         @check-all="onCheckAllStateChange"
                         @sort-change="onSortChange"
                         :key="column.field"
                         :column="column"
                         :level="0"
                         :root-config="rootConfig"
                         :cur-sorting="curSorting"
                         :heights="settings.heights"></d-g-header-cell>
      </div>
      <div class="dg-header-normal-blank dg-header-bottom-border"></div>
    </div>
    <div class="dg-right-fixed-wrapper" :style="{left: (leftFixedWidth + centerWidth) + 'px'}">
      <d-g-header-cell v-for="column in settings.rightFixedColumns"
                       @start-resize="startResize"
                       @check-all="onCheckAllStateChange"
                       @sort-change="onSortChange"
                       :key="column.field"
                       :column="column"
                       :level="0"
                       :root-config="rootConfig"
                       :cur-sorting="curSorting"
                       :heights="settings.heights"></d-g-header-cell>
    </div>
    <div class="dg-header-scrollbar-space" :style="{width: scrollbarWidth + 'px'}"></div>
  </div>
</template>

<script>
  import _ from 'lodash'
  import DGHeaderCell from './DGHeaderCell.vue'
  import utils from '../utils'

  export default {
    components: {DGHeaderCell},
    props: {
      rootConfig: {
        type: Object,
        default () {
          return {}
        }
      },
      curSorting: {
        type: Object,
        default () {
          return null
        }
      },
      width: Number,
      settings: {
        type: Object,
        default () {
          return {
            leftFixedColumns: [],
            rightFixedColumns: [],
            normalColumns: [],
            heights: []
          }
        }
      }
    },
    data () {
      return {
        currentResizingColumn: null,
        resizeStartX: null,
        headerHeight: 0,
        leftFixedWidth: 0,
        rightFixedWidth: 0,
        normalColumnsWidth: 0,
        normalColumnsScroll: 0,
        scrollbarWidth: utils.scrollBarWidth
      }
    },
    methods: {
      onSortChange (column, sort) {
        this.$emit('sort-change', column, sort)
      },
      startResize ($event, column, isRightFixed) {
        this.resizeStartX = $event.clientX
        this.currentResizingColumn = {column, isRightFixed}
        document.body.style.cursor = 'col-resize'
        document.removeEventListener('mousemove', this.doResize)
        document.addEventListener('mousemove', this.doResize)
        document.removeEventListener('mouseup', this.stopResizing)
        document.addEventListener('mouseup', this.stopResizing)
      },
      doResize ($event) {
        if (this.currentResizingColumn) {
          let width = this.currentResizingColumn.column._width +
            (this.currentResizingColumn.isRightFixed ? -1 : 1) * ($event.clientX - this.resizeStartX)
          if (width < this.rootConfig.minColumnWidth) {
            return
          }
          this.currentResizingColumn.column.width = width
          this.resizeStartX = $event.clientX
          this.$emit('col-resize')
        }
      },
      stopResizing () {
        document.body.style.cursor = ''
        this.currentResizingColumn = null
        document.removeEventListener('mousemove', this.doResize)
        document.removeEventListener('mouseup', this.stopResizing)
      },
      refreshPosition () {
        let widths = _.map([this.settings.leftFixedColumns, this.settings.rightFixedColumns, this.settings.normalColumns],
          item => {
            if (item && item.length > 0) {
              return _.sum(_.map(item, col => { return col._width }))
            }
            return 0
          })
        this.leftFixedWidth = widths[0]
        this.rightFixedWidth = widths[1]
        this.normalColumnsWidth = widths[2]
      },
      setNormalColumnsScroll (offset) {
        this.normalColumnsScroll = -offset
      },
      onCheckAllStateChange (isAllChecked) {
        this.$emit('check-all', isAllChecked)
      }
    },
    computed: {
      centerWidth () {
        let width = this.width - this.leftFixedWidth - this.rightFixedWidth
        if (width < 0) {
          width = 0
        }
        let actualWidth = this.leftFixedWidth + this.rightFixedWidth + width
        this.$emit('dg-overflow', actualWidth < this.width ? actualWidth : 0)
        return width
      },
      normalColumnsWrapperStyle () {
        return {
          left: `${this.leftFixedWidth}px`,
          width: `${this.centerWidth}px`,
          height: `${this.headerHeight}px`,
          position: 'absolute',
          overflow: 'hidden'
        }
      },
      normalColumnsStyle () {
        return {
          position: 'relative',
          height: '100%',
          width: `${this.normalColumnsWidth}px`,
          left: `${this.normalColumnsScroll}px`
        }
      }
    },
    watch: {
      settings () {
        this.headerHeight = this.settings.heights[0]
        this.refreshPosition()
      }
    },
    destroyed () {
      document.removeEventListener('mousemove', this.doResize)
      document.removeEventListener('mouseup', this.stopResizing)
    }
  }
</script>
